大家好,我是Leo
今天要來講解的是filter使用上的一些方法
OK~~~ Let's go now!!!
類似 mysql 語法內的 where fieldname = value
昨天我們有操作一些模糊比對的filter,如下圖
如果名字有一個字包含則顯示
name = request.data.get("name")
hotpots = hotpots.filter(name__icontains=name)
假設我們今天要找出薪水在一定區間內的員工
firstname、lastname、tel、roleName 和 roleSaraly概念圖如下:
如沒有資料,請各位使用之前製作的API先新增幾筆資料進去DB
薪水區間最低在lower,最高在upper
~Q filer : first_name or last_name (不包含的value)
有request.data 才篩選,無則pass
最後排序object的id
views/roles_filter.py
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import generics,permissions
from website.models import Users
from website.serializers import RolesFilterSerializer
from django.db.models import Q
class RolesFilterAPIView(APIView):
permission_classes = (permissions.AllowAny,)
authentication_classes = []
def post(self, request):
users = Users.objects.all()
try:
name_exclude = request.data.get("nameExclude")
users = users.filter(~Q(auth_user__first_name__icontains=name_exclude)&
~Q(auth_user__last_name__icontains=name_exclude))
except:
pass
try:
lower = request.data.get("lower")
users = users.filter(role__salary__gte=lower)
except:
pass
try:
upper = request.data.get("upper")
users = users.filter(role__salary__lte=upper)
except:
pass
users = users.order_by('id')
serializer_users = RolesFilterSerializer(
users, many=True, context={"request": request}
)
return Response(serializer_users.data)
views/init.py
from .roles_filter import *
serializers/roles_filter_ser.py
from rest_framework import serializers
from website.models import Users
class RolesFilterSerializer(serializers.ModelSerializer):
firstName = serializers.CharField(source='auth_user.first_name')
lastName = serializers.CharField(source='auth_user.last_name')
roleName = serializers.CharField(source='role.name')
roleSalary = serializers.CharField(source='role.salary')
class Meta:
model = Users
fields = ('id','firstName','lastName','tel','roleName','roleSalary')
serializers/init.py
from .roles_filter_ser import *
urls.py
from website.views import (
RolesFilterAPIView
)
urlpatterns = [
path('api/role/filter',RolesFilterAPIView.as_view(),name='api-role-filter')
]
users table
user_roles table
最低薪水15000(含以上) & nameExclude (lastName,firstName不包含的字段)
今天主要是介紹一些filer的基本用法
今天如果要使用ForeignKey資料篩選的方法及
filter 不包含的篩選方法
明天我想介紹的是serializer的進階用法
我們明天見,各位掰掰~~~